<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <img src="../../assets/images/avatar.jpg" alt="" class="preview" v-if="url === ''" />
    <img :src="url" alt="" class="preview" v-else />
    <div style="margin-top: 10px">
      <el-button type="primary" @click="$refs.fileRef.click()"><i class="el-icon-plus"></i>添加头像</el-button>
      <el-button type="success" @click="updateAvatar" ref="upload" :disabled="url === ''">
        <i class="el-icon-upload"></i>上传头像</el-button
      >
      <input type="file" style="display: none" ref="fileRef" @change="preview" />
    </div>
  </el-card>
</template>
<script>
import { updateAvatarAPI } from '@/api/user'
export default {
  data() {
    return {
      url: ''
    }
  },
  methods: {
    preview(e) {
      if (e.target.files.length > 0) {
        // 说明选择了图片
        // 获取文件对象
        const fileObj = e.target.files[0]
        // console.log(fileObj)
        const fr = new FileReader()
        fr.readAsDataURL(fileObj)
        fr.onload = () => {
          this.url = fr.result
        }
        // 说明没有选择图片
      } else {
        return false
      }
    },
    async updateAvatar() {
      const { data: res } = await updateAvatarAPI(this.url)
      console.log(res)
      if (res.code === 0) {
        // 调用 vuex 中的 actions中的 getUser 方法，更新用户数据
        this.$store.dispatch('user/getUser')
        this.$message.success(res.message)
      } else {
        this.$message.error(res.message)
      }
    }
  }
}
</script>
<style lang="less" scoped>
.preview {
  object-fit: cover;
  width: 350px;
  height: 350px;
}
</style>
